<?php
/**
 * (model) CN-海外仓发货装箱（批次）（国内发海外仓）
 */
namespace App\Models\OverSeasIn;

use App\Models\Basics\SysArea;
use App\Models\OverSeasBa\Warehouse;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class DeliveryBox extends Model
{
    protected $table = 'os_in_delivery_box';

    protected $guarded = [];

    public static $_status = [
        1 => '待入库',
        2 => '部分入库',
        3 => '完全入库',
    ];

    //到货异常状态
    public static $_esStatus = [
        1 => '待校验',
        2 => '正常',
        3 => '异常',//默认时效内未完全到货
    ];

    public static $_esDeal = [
        1 => '待处理',
        2 => '已入库',
        3 => '已赔付',
    ];

    public function delivery(){
        return $this->belongsTo(Delivery::class,'delivery_no','delivery_no');
    }

    public function box_detail(){
        return $this->hasMany(DeliveryBoxDetail::class,'delivery_box_id','id');
    }

    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public function skuClassify(){
        return $this->hasOneThrough(
            ProductClassify::class,
            ProductSku::class,
            'id',//中间表
            'id',//目标表
            'psku_id',//当前模型
            'classify_id'//中间表
        );
    }

    public function warehouse(){
        return $this->belongsTo(Warehouse::class,'warehouse_id');
    }

    public function area(){
        return $this->belongsTo(SysArea::class,'area_id');
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function($deliveryBox) {
            $deliveryBox->box_detail()->delete();
        });
    }

    public static function storageTotalNum($deliveryNo,$fnSku){
        return DeliveryBox::query()
            ->where('delivery_no',$deliveryNo)
            ->where('fnsku',$fnSku)
            ->sum(DB::raw('storage_total*num_per_box'));
    }
}
